package classes;

import interfaces.ListListener;

import java.util.ArrayList;
import java.util.List;

public class ObservableList<E> extends ArrayList<E> {

	private static final long serialVersionUID = -8029458167949629685L;
	
	private final List<ListListener> listeners = new ArrayList<ListListener>();
	
	@Override
	public boolean add(E e) {
		super.add(e);
		notifyListeners();
		return true;
	}

	@Override
	public boolean remove(Object o) {
		boolean res = super.remove(o);
		if (res)
			notifyListeners();
		return res;
	}
	
	public void addListener(ListListener listener) {
        synchronized (listeners) {
            listeners.add(listener);
        }
    }
 
    public void removeListener(ListListener listener) {
        synchronized (listeners) {
            listeners.remove(listener);
        }
    }
 
    private void notifyListeners() {
        synchronized (listeners) {
            for (ListListener listener : listeners) {
                listener.onListChanged();
            }
        }
    }
}
